var data1 = []
var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
var isMsn="否";
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}

function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}

let operationList=[];
let salesmanList=[];
let deptOperationList=[];
let deptSalesmanList=[];

//select over
(function () {
    //获取当前用户的部门及人员结构树
    let treeList = getCurrentDepartmentUser();

    if(treeList && treeList.list){
        let userTree = getAllJson(treeList.list);
        operationList= getxmselect("#operationCode","operationCode", userTree);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", userTree);
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}]);
        salesmanList=getxmselect("#salesmanCode","salesmanCode", [{name: user.name, value: user.code}]);
    }

    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
        deptSalesmanList = getxmselect("#deptSalesmanCode", "deptSalesmanCode", [{name: user.name, value: user.code}]);
    }

})()

form.render();//表单刷新
var data2=[]
table.render({
    elem: '#foreignexchangesettlementselect'
    ,data:data2
    ,url:'clearChange/selectAllchangeByPage'
    ,toolbar: '#foreignexchangesettlementtoolbar'
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true, totalRowText: '合计'}
        ,{field:'billType', title:'单据类型',sort:true,width: 120,templet: function(d){
                var re=""
                if(d.status==1){
                    re="草稿箱"
                }else if(d.status==2){
                    re="待批箱"
                }else if(d.status==3){
                    re="已批箱"
                }else if(d.status==4){
                    re="完成箱"
                }else if(d.status==5){
                    re="垃圾箱"
                }
                return re;
            }}
        ,{field:'companyName', title:'签约公司 ',sort:true,width: 120}
        ,{field:'invoiceNo', title:'发票编号',sort:true,width: 120,event: "invoicenumber"}
        ,{field:'customerName', title:'客户名称',sort:true,width: 120}
        ,{field:'customerLevelName', title:'客户级别',sort:true,width: 120}
        ,{field:'invoiceDate', title:'发票日期',sort:true,width: 120}
        ,{field:'shippingDate', title:'出运日期',sort:true,width: 120}
        ,{field:'settleDate', title:'预计收汇日期',sort:true,width: 120}
        ,{field:'moneyKind', title:'币种',sort:true,width: 120}
        ,{field:'actualAtd', title:'实际开船日期ATD ',sort:true,width: 200}
        ,{field:'instockDate', title:'进仓装柜日期 ',sort:true,width: 180}
        ,{field:'settleMode', title:'收款(清关)方式',sort:true,width: 120}
        ,{field:'priceTerm', title:'价格术语',sort:true,width: 120}
        ,{field:'invoiceMoney', title:'发票总额',sort:true,width: 120, totalRow: true}
        ,{field:'clearAllPlace', title:'清关总额',sort:true,width: 120, totalRow: true}
        ,{field:'createTime', title:'制单日期',sort:true,width: 120}
        ,{field:'contractNo', title:'销售合同号',sort:true,width: 120}
        ,{field:'custContractNo', title:'客户合同号',sort:true,width: 120}
        ,{field:'salesman', title:'业务员',sort:true,width: 120}
        ,{field:'businessMode', title:'业务模式',sort:true,width: 120}
        ,{field:'asPerInNo', title:'As Per IN No',sort:true,width: 140}
        ,{field:'stock', title:'仓库',sort:true,width: 120}
        ,{field:'overdue', title:'逾期',sort:true,width: 120}
        ,{field:'payday', title:'账期',sort:true,width: 120}
        ,{field:'bankName', title:'银行 ',sort:true,width: 120}
        ,{field:'opname', title:'操作员',sort:true,width: 120}
        ,{field:'totalTariffAmount', title:'关税总金额',sort:true,width: 120}
        ,{field:'usdRate', title:'美元汇率',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'startPlace', title:'起运地',sort:true,width: 120}
        ,{field:'endPlace', title:'目的地',sort:true,width: 120}
        // ,{fixed: 'right', width:240, toolbar: '#foreignexchangesettlementeditor', title:'操作'}
        ,{fixed: 'right', width:240, title:'操作', templet: function(d){
                        if(isMsn=="是"){
                            var html="<div>"
                            if(d.status==1 || d.status==2 || d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                            }
                            if(d.status==1){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                            }
                            if(d.status==2 || d.status==3 ||d.status==4){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                            }
                            if(d.status==3){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                            }
                            if(d.status==1){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delete\">删除</a>"
                            }
                            if(d.status==5){
                                html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delectYes\">彻底删除</a><a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"reduction\">还原</a>"
                            }
                            return html+"</div>";
                        }else {
                            var html = "<div>"
                            if (d.status == 1 || d.status == 2) {
                                html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                            }
                            if (d.status == 1) {
                                html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>"
                            }
                            return html + "</div>";
                        }
            }
        }
    ]]
    ,id: 'foreignexchangesettlementtableid'
    ,height: $(document).height() - $('#foreignexchangesettlementselect').offset().top - 50
    ,page: true
});



table.on('tool(foreignexchangesettlementtable)', function(obj){
    var data = obj.data;
    var id=obj.data.clearId;
    if(obj.event === 'update') {
        parent.intab("views/jsp/ExportBusiness/tpl/billClearChange.jsp?id="+id,"修改清关")
    }else if(obj.event === 'delectYes'){
        layer.confirm('真的删除行么', function (index) {
            $.ajax({
                url: 'clearChange/deleteBillById?clearId='+id,
                type: 'GET',
                success: function (date) {
                    layer.msg('删除成功');
                }
            });
            obj.del();
            layer.close(index);
        });
    }else if(obj.event === 'submits'){
        layer.confirm('确定提交审批吗', function (index) {
            changeStatues(id,3)
            layer.msg('提交审批');
        });
    }else if(obj.event === 'through'){
        layer.confirm('确定审批通过吗', function (index) {
            changeStatues(id,3)
            layer.msg('审批通过');
        });
    }else if(obj.event === 'backtothe'){
        layer.confirm('确定审批退回吗', function (index) {
            changeStatues(id,1)
            layer.msg('审批退回');
        });
    }else if(obj.event === 'complete'){
        layer.confirm('确定完成吗', function (index) {
            changeStatues(id,4)
            layer.msg('完成');
        });
    }else if(obj.event === 'reduction'){
        layer.confirm('确定还原吗', function (index) {
            changeStatues(id,1)
            layer.msg('还原');
        });
    }else if(obj.event === 'delete'){
        layer.confirm('确定删除吗', function (index) {
            changeStatues(id,5)
            layer.msg('删除');
        });
    }else if (obj.event === "invoicenumber"){
        parent.intab("views/jsp/ExportBusiness/tpl/billClearShow.jsp?id="+id,"清关明细")
    }
    form.render()
});

function changeStatues(id,statues){
    $.ajax({
        url: 'clearChange/changeBillById?clearId='+id+"&statues="+statues,
        type: 'GET',
        success: function (date) {
            table.reload("foreignexchangesettlementtableid",{
                url: 'clearChange/selectAllchangeByPage'
            })
        }
    });
}

layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("costStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/ExportBusiness/billClear1.jsp","清关发票费用统计")
                break
            case "s2":
                parent.intab("views/jsp/ExportBusiness/billClear2.jsp","清关单据产品统计")
                break
        }
    });
})

form.on('submit(submitform)', function(data){
    let operationCode = data.field.operationCode;
    let salesmanCode = data.field.salesmanCode;
    if(salesmanCode==""&&operationCode==""){
        var sm = getManageRule("BillExchangeSm")//业务员
        var codeList =""
        for(let i in sm){
            if(codeList==""){
                codeList = sm[i].code;
            }else{
                codeList = codeList + "," + sm[i].code;
            }
        }
        data.field.salesmanCode = codeList;
        var op = getManageRule("BillExchangeOp");//操作员
        var codeList =new Array();
        for(let i in op){
            if(codeList==""){
                codeList = op[i].code;
            }else{
                codeList = codeList + "," + op[i].code;
            }
        }
        data.field.operationCode = codeList;
    }

    table.reload('foreignexchangesettlementtableid', {
        data:data1 ,
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

layui.use(['dropdown'], function () {
    var dropdown = layui.dropdown;
    dropdown.onFilter("printfn", function (event) {
        var checkStatus = table.checkStatus("foreignexchangesettlementtableid");
        $.ajax({
            url: 'billDeclare/selectLogo?declare_id='+checkStatus.data[0].clearId,
            type: 'GET',
            async: false, // 同步
            success: function (date) {
            },
        });
        switch (event) {
            case "printfn1":
                console.log(checkStatus.data.length)
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个清关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的清关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billExchange1&code=code:"+checkStatus.data[0].clearId)
                break;
            case "printfn2":
                if(checkStatus.data.length > 1){
                    layer.msg( "每次只能打印一个清关单据! ");
                    break;
                }
                if(checkStatus.data.length == 0){
                    layer.msg("请选择要打印的清关单据! ");
                    break;
                }
                window.open("views/jsp/report.jsp?ym=billExchange2&code=code:"+checkStatus.data[0].clearId)
                break;
        }
    });
})
function downLogo(url){
    $.ajax({
        url: 'ftp/onLine2?pathString='+url,
        type: 'GET',
        async: false, // 同步
        success: function (date) {
        },
    });
}


table.on('toolbar(foreignexchangesettlementtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'news':
            parent.intab("views/jsp/ExportBusiness/tpl/billClearSet.jsp","新增清关")
            break;
    };
});

$("#statistical").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/statistics.jsp","清关统计")
});
$("#settlementexchangetargets").on("click",function () {
    parent.intab("views/jsp/ExportBusiness/tpl/settlementexchangetargets.jsp","清关目标")
});

$(document).ready(function () {
    $.ajax({
        url: 'clearChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
    $.ajax({
        url: 'clearChange/selectAllcompanyAndpeople',
        type: 'GET',
        success: function (date) {
            var map=date.data
            var company=[]
            $.each(map, function (key, value) {
                if(key=="companyName"){
                    company=value
                }
            });
            for(let i in company){
                $("#company_code").append("<option value='"+company[i].code+"'>"+company[i].name+"</option>")
            }

            form.render();
        }
    });

});
$("#clear").on("click",function () {
    operationList.setValue([ ]);
    salesmanList.setValue([ ]);
    deptOperationList.setValue([ ]);
    deptSalesmanList.setValue([ ]);
});